package user;

import com.mchange.v2.c3p0.ComboPooledDataSource;

import java.net.URL;
import java.sql.*;

public class DBUtil {
    //获得conn对象的
    public static Connection getConn(){
        Connection conn = null;
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            String  url = "jdbc:mysql://127.0.0.1:3306/enterprise_db";
            String username = "root";
            String password = "hmh061222";
            conn = DriverManager.getConnection(url, username, password);
        } catch (ClassNotFoundException | SQLException e) {
            e.printStackTrace();
        }
        return conn;
    }


    //关闭操作的一个封装；
    public static void colseAll(Connection conn, PreparedStatement pstmt, ResultSet rs){
        if(conn!=null){
            try {
                conn.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
        if(pstmt!=null){
            try {
                pstmt.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
        if(rs!=null){
            try {
                rs.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
    }

    // 注册界面用到的连接
    public static Connection getConnection() throws SQLException {
        ComboPooledDataSource dataSource = new ComboPooledDataSource();

            try {
                dataSource = new ComboPooledDataSource(); // 不使用命名配置
                dataSource.setDriverClass("com.mysql.jdbc.Driver");
                dataSource.setJdbcUrl("jdbc:mysql://127.0.0.1:3306/enterprise_db");
                dataSource.setUser("root");
                dataSource.setPassword("hmh061222");

                // 手动设置连接池参数
                dataSource.setInitialPoolSize(5);
                dataSource.setMaxPoolSize(20);
                dataSource.setMinPoolSize(5);
                dataSource.setAcquireIncrement(5);
                dataSource.setMaxIdleTime(1800);
            } catch (Exception e) {
                throw new RuntimeException("初始化失败", e);
            }

        return dataSource.getConnection();
    }

    public static void closeConnection(Connection conn) {
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}
